package com.jaws.core.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.google.common.base.Charsets;

import java.io.UnsupportedEncodingException;
import java.util.List;

public class JsonUtil {
	public static final <T> T parse(String text, Class<T> clazz) {
		return JSON.parseObject(text, clazz);
	}

	public static final <T> T parse(String text) {
		return (T) JSON.parse(text);
	}

	public static final <T> T parse(byte[] input, Class<T> clazz) {
		return JSON.parseObject(input, clazz, new Feature[0]);
	}

	public static final <T> T parse(byte[] input) {
		return (T) JSON.parse(input, new Feature[0]);
	}

	public static final <T> List<T> parseArray(String text, Class<T> clazz) {
		return JSON.parseArray(text, clazz);
	}

	public static final <T> List<T> parseArray(byte[] input, Class<T> clazz) {
		try {
			return JSON.parseArray(new String(input, "UTF-8"), clazz);
		} catch (UnsupportedEncodingException arg2) {
			throw new RuntimeException(arg2);
		}
	}

	public static final String toJSONString(Object object) {
		// 设置 JSON 输出格式
		return JSON.toJSONString(object,
				// 设置 SerializerFeature ...
				// 格式化输出;PS:日志输出问题，这里不开启格式化
				// SerializerFeature.PrettyFormat,
				// 输出key时是否使用双引号,默认为true
				SerializerFeature.QuoteFieldNames,
				// 空值处理
				SerializerFeature.WriteNullStringAsEmpty,
				SerializerFeature.WriteMapNullValue,
				SerializerFeature.WriteNullListAsEmpty,
				// 消除对同一对象循环引用的问题，默认为false
				SerializerFeature.DisableCircularReferenceDetect,
				// 格式化日期
				SerializerFeature.WriteDateUseDateFormat
		);
	}

	public static final String toJSONString(Object object, String dateFormat) {
		return JSON.toJSONStringWithDateFormat(object, dateFormat, new SerializerFeature[0]);
	}

	public static final byte[] toJSONBytes(Object object) {
		return JSON.toJSONBytes(object, new SerializerFeature[0]);
	}
}
